﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

/// <summary>
/// Summary description for SortListView
/// </summary>
public class SortListView
{

    public static int? SortMyView(object sender, ListViewItemEventArgs args, int? _sortCellIndex)
	{
        ListView listView = (ListView)sender;

        //  if there is no sort expression, don't bother
        if (listView.SortExpression.Length > 0)
        {
            //  if this is the first time ItemDataBound has fired, figure out what column
            //  is being sorted by
            if (!_sortCellIndex.HasValue)
            {
                HtmlTableRow header = ((HtmlTable)listView.FindControl("header")).Rows[0];

                //  loop through the cells and find the one that contains the linkbutton
                //  with the commandargument of the ListView's current SortExpression
                for (int i = 0; i < header.Cells.Count; i++)
                {
                    HtmlTableCell th = header.Cells[i];
                    //  find the LinkButton control
                    foreach (Control c in th.Controls)
                    {
                        LinkButton linkButton = c as LinkButton;
                        if (linkButton != null && linkButton.CommandArgument == listView.SortExpression)
                        {
                            //  keep track of the cell index
                            _sortCellIndex = i;

                            //  add the sort class to this item                        
                            string originalHeaderStyle = th.Attributes["class"];
                            th.Attributes["class"] = string.Format("{0} {1}", originalHeaderStyle, listView.SortDirection == SortDirection.Ascending ? "sortasc" : "sortdesc").Trim();
                            break;
                        }
                    }
                }
            }

            //  set the cells css class as well
            HtmlTableRow tr = (HtmlTableRow)args.Item.FindControl("row");
            HtmlTableCell td = tr.Cells[_sortCellIndex.Value];
            string originalCellStyle = td.Attributes["class"];
            td.Attributes["class"] = string.Format("{0} {1}", originalCellStyle, "sort").Trim();
            
        }
        return _sortCellIndex;
	}
}
